package com.osfw.framework.web.service;

import com.osfw.framework.constants.Constants;
import com.osfw.framework.exception.UserException;
import com.osfw.framework.manager.AsyncFactory;
import com.osfw.framework.manager.AsyncManager;
import com.osfw.framework.utils.ImageUtil;
import com.osfw.framework.utils.MessageUtils;
import com.osfw.framework.utils.StringUtils;
import com.osfw.system.entity.manage.SysUser;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Component;

/**
 * 登录密码方法
 */
@Component
public class PasswordService {

    // private Cache<String, AtomicInteger> loginRecordCache;

    /*@Value(value = "${user.password.maxRetryCount}")
    private String maxRetryCount;*/

    public void validate(SysUser user, String password) {
        String loginName = user.getLoginName();

        /*AtomicInteger retryCount = loginRecordCache.get(loginName);

        if (retryCount == null) {
            retryCount = new AtomicInteger(0);
            loginRecordCache.put(loginName, retryCount);
        }
        if (retryCount.incrementAndGet() > Integer.valueOf(maxRetryCount).intValue()) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount)));
            UserException.throwUserPasswordRetryLimitExceedException(Integer.valueOf(maxRetryCount).intValue());
        }*/

        if (!matches(user, password)) {
            // AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.count", retryCount)));
            // loginRecordCache.put(loginName, retryCount);
            UserException.throwUserPasswordNotMatchException();
        } else {
            clearLoginRecordCache(loginName);
        }
    }

    public boolean matches(SysUser user, String newPassword) {
        return user.getPassword().equals(encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
    }

    public void clearLoginRecordCache(String loginName) {
        // loginRecordCache.remove(loginName);
    }

    public String encryptPassword(String loginName, String password, String salt) {
        return new Md5Hash(StringUtils.join(loginName, password), salt, 3).toHex();
    }

    public String randomSalt() {
        // 一个Byte占两个字节，此处生成的3字节，字符串长度为6
        SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
        return secureRandom.nextBytes(3).toHex();
    }

}
